package com.happy.zebra.im.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.happy.zebra.im.api.entity.ImDismissGroupLog;
import com.happy.zebra.im.api.vo.CreateGroupVO;
import com.happy.zebra.im.service.ImDismissGroupLogService;
import com.happy.zebra.im.utils.ImUtil;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.util.R;
import io.rong.models.group.GroupModel;
import io.rong.models.response.GroupUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Api(value = "IM", tags = "IM")
@RestController
@AllArgsConstructor
@RequestMapping("/im")
public class IMController {


	private ImDismissGroupLogService logService;

	@ApiOperation("获取融云token")
	@GetMapping("getToken")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户在 App 中的唯一标识码", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "username", value = "用户名称", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "portrait", value = "用户头像 URI", paramType = "query", dataType = "String")
	})
	public R getToken(String userId, String username, String portrait) throws Exception {
		return new R(ImUtil.getToken(userId, username, portrait));
	}

	@ApiOperation("创建群组")
	@PostMapping("createGroup")
	public R createGroup(@RequestBody CreateGroupVO createGroupVO) {

		//生成 groupId
		String groupId = UUID.randomUUID().toString().replace("-", "");
		try {
			if (ImUtil.createGroup(createGroupVO.getUserIds(), createGroupVO.getGroupName(), groupId)) {
				return new R(groupId);
			} else {
				return new R(CommonConstants.FAIL, "网络异常，请您稍后再试", false);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new R(CommonConstants.FAIL, e.getMessage(), false);
		}

	}

	@ApiOperation("解散群组")
	@PostMapping("groupDismiss")
	public R groupDismiss(@RequestBody CreateGroupVO createGroupVO) {
		try {

			Object data = getGroupUsers(createGroupVO.getGroupId()).getData();

			if (data != null) {
				List<GroupUser> users = (List<GroupUser>) data;
				List<String> userIds = users.stream().map(x -> x.getId()).collect(Collectors.toList());

				for (String userId : userIds) {
					//存入解绑记录表中
					ImDismissGroupLog log = new ImDismissGroupLog();
					log.setGroupId(createGroupVO.getGroupId());
					log.setImUserId(userId);
					logService.save(log);
				}

				return new R(ImUtil.groupDismissResult(createGroupVO.getGroupId(), userIds));
			} else {
				return new R(ImUtil.groupDismissResult(createGroupVO.getGroupId(), null));
			}

		} catch (Exception e) {
			e.printStackTrace();
			return new R(CommonConstants.FAIL, e.getMessage(), false);
		}
	}

	@SneakyThrows
	@ApiOperation("编辑群组成员")
	@PostMapping("updGroupUsers")
	public R updGroupUsers(@RequestBody CreateGroupVO createGroupVO) {
		//先将此分组成员全部移除
		List<GroupUser> groupUsers = ImUtil.groupQueryUser(createGroupVO.getGroupId());
		List<String> userIds = groupUsers.stream().map(x -> x.getId()).collect(Collectors.toList());
		ImUtil.groupQuit(userIds, createGroupVO.getGroupId(), createGroupVO.getGroupName());
		//加入分组
		ImUtil.groupJoin(createGroupVO.getGroupId(), createGroupVO.getGroupName(), createGroupVO.getUserIds());
		return new R(true);
	}

	@SneakyThrows
	@ApiOperation("查询群组里的用户")
	@GetMapping("getGroupUsers")
	public R getGroupUsers(String groupId) {
		List<GroupUser> users = ImUtil.groupQueryUser(groupId);
		return new R(users);
	}

	@SneakyThrows
	@ApiOperation("根据用户ID获取其所在的群")
	@GetMapping("getGroupByUserId")
	public R<GroupModel[]> getGroupByUserId(String imUserId) {
		return new R<>(ImUtil.getUserGroups(imUserId));
	}


//	@ApiOperation("根据 targetId 获取群组/单用户的基本信息")
//	@GetMapping("getTargetDetail")
//	@ApiImplicitParams({
//			@ApiImplicitParam(name = "targetId", value = "targetId", paramType = "query", dataType = "String"),
//			@ApiImplicitParam(name = "flg", value = "用户/群组标识 0-用户 1-群组", paramType = "query", dataType = "String")
//	})
//	public R getTargetDetail(String targetId, String flg) {
//
//		//用户信息
//		if ("0".equals(flg)) {
//
//		}
//		//群组信息
//		else if ("1".equals(flg)) {
//
//		}
//		//其他
//		else {
//			return new R(CommonConstants.FAIL, "flg参数不正确", false);
//		}
//	}

	@ApiOperation("根据用户IM-ID 获取其解绑过的群")
	@GetMapping("getDismissLogByImId")
	public R getDismissLogByImId(String imUserId) {

		List<ImDismissGroupLog> logs = logService.list(new QueryWrapper<ImDismissGroupLog>()
				.eq(ImDismissGroupLog.COL_IM_USER_ID, imUserId)
				.groupBy(ImDismissGroupLog.COL_GROUP_ID));

		List<String> resList = logs.stream().map(x -> x.getGroupId()).collect(Collectors.toList());

		return new R(resList);

	}

}
